package com.wing.oauth2.filter;

import com.wing.common.utils.JsonResult;
import com.wing.oauth2.exception.CabAuthException;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.UserAuthVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码过滤器
 *
 * @author
 */
//@Profile({"test","pro"})
@Component
public class CabAuthFilter extends OncePerRequestFilter {

    @Lazy
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;


    @Autowired
    private  UserClient userClient;


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
//        logger.info(httpServletRequest.getRequestURI());
//        logger.info(httpServletRequest.getMethod());
//        logger.info(httpServletRequest.getRemoteHost());
        String cabId = httpServletRequest.getParameter("cabId");
        String userName=httpServletRequest.getParameter("username");

        if ("/oauth2/admin/user/login".equalsIgnoreCase(httpServletRequest.getRequestURI()) && httpServletRequest.getMethod().equals("POST")) {

                if (StringUtils.isNotBlank(cabId)){
                    JsonResult<UserAuthVO> jsonResult= userClient.findUserByUsername(userName);
                    if (jsonResult==null||JsonResult.Code.SUCCESS.getCode()!=jsonResult.getCode()||jsonResult.getData()==null){
                        authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, new CabAuthException("获取用户失败"));
                        return;
                    }
                    if (StringUtils.isNotBlank(jsonResult.getData().getCabId())){
                        if (!(","+jsonResult.getData().getCabId()+",").contains(","+cabId+",")){
                            authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, new CabAuthException("该用户没有此主柜的权限，如果需要请配置用户拥有此主柜!"));
                            return;
                        }
                    }
                }

        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }



}